<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\CollectCourse;
use app\common\model\Course;
use app\common\model\CourseQuestion;
use app\common\model\UserCourse;

class ProfessionCourse
{
    /**
     * 课程详情
     * @param $param
     * @return array
     */
    public function getInfo($param): array
    {
        // 提取参数
        $id = $param['id'];
        $userId = $param['userId'];

        // 查询条件
        $where = [
            ['a.id', '=', $id]
        ];

        //输出字段
        $field = 'a.id,a.name,a.code,a.desc,a.version,b.status as collect,IFNULL(c.name,\'\') as category_name';

        //查询数据
        $info = app(Course::class)
            ->alias('a')
            ->leftJoin('collect_course b', 'a.id = b.course_id and b.status=1 and b.user_id=' . $userId)
            ->leftJoin('exam c', 'a.exam_id = c.id')
            ->field($field)
            ->where($where)
            ->find();
        $info = $info ? $info->toArray() : [];

        //查询是否课程VIP
        $info['isCourseVip'] = (new UserCourse())->checkHasCourse($userId, $id);

        //返回
        return $info;
    }

    /**
     * 选择课程列表
     * @param $param
     * @return array
     */
    public function getList($param): array
    {
        // 提取参数
        $userId = $param['userId'];
        $profession_id = $param['professions_id'];

        // 查询条件
        $where = [
            ['a.profession_id', '=', $profession_id],
            ['c.status', '=', 1]
        ];

        //输出字段
        $field = 'a.course_id,a.type,c.name,a.code,ifnull(b.id,0) bid';

        //查询数据
        $list = app(\app\common\model\ProfessionCourse::class)
            ->alias('a')
            ->leftJoin('collect_course b', 'a.course_id = b.course_id and b.status=1 and b.user_id=' . $userId)
            ->leftJoin('course c', 'a.course_id = c.id')
            ->field($field)
            ->where($where)
            ->select();
        $list = $list ? $list->toArray() : [];

        //构建数据
        $data = [
            [
                'group' => '已报考',
                'courses' => [],
            ],
            [
                'group' => '未报考',
                'courses' => [],
            ]
        ];
        foreach ($list as $val) {
            $joined = empty($val['bid']) ? 1 : 0;
            $data_val = [
                'code' => $val['code'],
                'type' => $val['type'],
                'id' => $val['course_id'],
                'joined' => intval(!$joined),
                'name' => $val['name']
            ];
            $data[$joined]['courses'][] = $data_val;
        }

        //返回
        return $data;
    }

    /**
     * 加入课程
     * @param $param
     * @throws BusinessException
     */
    public function join($param)
    {
        //提取参数
        $join = $param['join'];

        //组装数据
        $time = time();
        $data = [
            'user_id' => $param['userId'],
            'course_id' => $param['course_id'],
            'status' => $join != 1 ? 1 : 2,
            'a_time' => $time,
            'u_time' => $time,
        ];
        $result = app(CollectCourse::class)->replace(true)->save($data);
        if ($result === false) {
            throw new BusinessException('报考或者取消课程失败');
        }
    }

    /**
     * 搜索课程
     * @param $param
     * @return array
     */
    public function search($param): array
    {
        // 提取参数
        $keyword = $param['keyword'];

        // 查询条件
        $where = " MATCH(name) AGAINST ( '+" . $keyword . "' IN BOOLEAN MODE)";

        // 输出字段
        $field = 'id,name,code';

        // 查询数据
        $list = app(Course::class)
            ->field($field)
            ->where($where)
            ->limit(30)
            ->select();
        $list = $list ? $list->toArray() : [];

        // 尝试CODE查询
        $where = [['code', 'like', $keyword . '%']];
        $otherList = app(Course::class)
            ->field($field)
            ->where($where)
            ->select();
        $otherList = $otherList ? $otherList->toArray() : [];
        $list = array_merge($list, $otherList);

        // 提取课程Id
        $allCourseId = array_column($list, 'id');
        $allCourseDict = [];
        if ($allCourseId) {
            $where = [['course_id', 'in', $allCourseId]];
            $allCourseDict = (new CollectCourse())->where($where)->column(
                'course_id,status',
                'course_id'
            );
        }

        // 填充数据
        foreach ($list as $key => $val) {
            $collect = $allCourseDict[$val['id']]['status'] ?? 2;
            $allNameValue = [$val['name'], $val['code']];
            $allNameValue = array_filter($allNameValue);
            $list[$key]['name'] = join('|', $allNameValue);
            $list[$key]['collect'] = $collect;
        }

        // 返回
        return $list;
    }
}